<script lang="ts" setup>
import type { HandCardConsumptionApi } from '#/api/spa/handcard/asset';

import { nextTick, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryHandCardConsumptionV2 } from '#/api/spa/handcard/asset';
import { getDictOptions } from '#/utils';
import { DICT_SPA_TYPE } from '#/utils/dictSpa';

const props = defineProps<{
  cardId?: number;
}>();

const emit = defineEmits<{
  (e: 'summary', payload: any | null): void;
}>();

function renderCurrency({ cellValue }: { cellValue: unknown }) {
  return `¥${Number((cellValue as number) || 0).toFixed(2)}`;
}
function renderTime({ cellValue }: { cellValue: unknown }) {
  const v = cellValue as any;
  if (!v) return '';
  if (typeof v === 'number') return dayjs(v).format('YYYY-MM-DD HH:mm:ss');
  if (typeof v === 'string') {
    const d = dayjs(v);
    return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : v;
  }
  return '';
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: [
      {
        fieldName: 'onlyActive',
        label: '只查使用中',
        component: 'Switch',
        defaultValue: true,
        componentProps: { class: 80 },
      },
      { fieldName: 'billNumber', label: '账单号', component: 'Input' },
      {
        fieldName: 'detailStatus',
        label: '明细状态',
        component: 'Select',
        componentProps: {
          options: getDictOptions(
            DICT_SPA_TYPE.SPA_Consumption_Status,
            'string',
          ),
        },
      },
      {
        fieldName: 'timeRange',
        label: '时间范围',
        component: 'RangePicker',
        componentProps: { showTime: true },
      },
    ],
  },
  gridOptions: {
    minHeight: 300,
    columns: [
      { field: 'billNumber', title: '账单号', width: 180, showOverflow: true },
      {
        field: 'itemName',
        title: '项目/商品',
        minWidth: 180,
        showOverflow: true,
      },
      { field: 'quantity', title: '数量', width: 100 },
      {
        field: 'unitPrice',
        title: '单价',
        width: 120,
        formatter: renderCurrency,
      },
      {
        field: 'subtotalAmount',
        title: '金额',
        width: 140,
        formatter: renderCurrency,
      },
      {
        field: 'status',
        title: '状态',
        width: 120,
        cellRender: {
          name: 'CellDict',
          props: { type: DICT_SPA_TYPE.SPA_Consumption_Status },
        },
      },
      { field: 'startTime', title: '时间', width: 180, formatter: renderTime },
    ],
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_ctx, formValues) => {
          if (!props.cardId) return [];
          const { timeRange, onlyActive, billNumber, detailStatus } =
            formValues || {};
          const [start, end] = Array.isArray(timeRange) ? timeRange : [];
          const payload: HandCardConsumptionApi.ConsumptionQueryV2 = {
            cardId: props.cardId,
            onlyActive: onlyActive ?? true,
            billNumber: billNumber || undefined,
            detailStatus: detailStatus || undefined,
            createTimeStart: start
              ? start.format?.('YYYY-MM-DD HH:mm:ss')
              : undefined,
            createTimeEnd: end
              ? end.format?.('YYYY-MM-DD HH:mm:ss')
              : undefined,
            pageNo: 1,
            pageSize: 100,
          };
          try {
            const resp = await queryHandCardConsumptionV2(payload);
            const body = resp as any;
            const dataWrap = body?.data ?? body;
            const first =
              Array.isArray(dataWrap?.list) && dataWrap.list.length > 0
                ? dataWrap.list[0]
                : null;
            if (!first) {
              emit('summary', null);
              return [] as any;
            }
            const summary = {
              status: first?.overallStatus,
              durationMinutes: first?.totalDurationMinutes,
              totalAmount: first?.totalAmount,
              paidAmount: first?.paidAmount,
              payableAmount: first?.pendingAmount,
              discountAmount: first?.totalDiscountAmount,
              consumptionBill: first?.currentBill,
            };
            emit('summary', summary);
            const rowsFromBill = Array.isArray(first?.billConsumptionDetails)
              ? (first.billConsumptionDetails as any[]).flatMap((b: any) =>
                  (b?.details || []).map((d: any) => ({
                    ...d,
                    billNumber: b?.bill?.billNumber,
                  })),
                )
              : [];
            const rows =
              rowsFromBill.length > 0
                ? rowsFromBill
                : Array.isArray(first?.allConsumptionDetails)
                  ? (first!.allConsumptionDetails as any[]).map((d: any) => ({
                      ...d,
                      billNumber: first?.currentBill?.billNumber,
                    }))
                  : [];
            return rows;
          } catch {
            message.error('获取消费明细失败');
            emit('summary', null);
            return [] as any;
          }
        },
      },
    },
    toolbarConfig: {
      search: true,
      refresh: true,
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
  },
});

defineExpose({ gridApi });

watch(
  () => props.cardId,
  async (val) => {
    if (!val) {
      emit('summary', null);
      return;
    }
    await nextTick();
    await gridApi.query();
  },
  { immediate: true },
);
</script>

<template>
  <Grid />
</template>

<style scoped></style>
